<?php
/**
 * 数据列表(分页，查询，排序)函数
 */
//类型比较符数组
class DataList {
	static $symbol = array(
						"1"=>"=", 
						"2"=>"like", 
						"3"=>">",
						"4"=>"<",
						"5"=>">=",
						"6"=>"<=",
						"7"=>"<>"
					);
	static $types = array(
						"char"=>1,
						"varchar"=>1,
						"tinytext"=>1,
						"text"=>1,
						"mediumtext"=>1,
						"longtext"=>1,
						"tinyint"=>2,
						"smallint"=>2,
						"mediumint"=>2,
						"int"=>2,
						"bigint"=>2,
						"float"=>2,
						"double"=>2,
						"date"=>3,
						"time"=>3,
						"datetime"=>3,
						"timestamp"=>3
					);
	static function getFields($db,$table){
		$stmt = $db->query( "DESCRIBE ".$table);
		$result = $stmt->fetchAll( PDO::FETCH_ASSOC );
		$stmt = null;
		$arr = array();
		foreach ($result as $f){
			$matchs = array();
			preg_match('/^\w+/',$f['Type'],$matchs);
			$arr[$f['Field']] = $matchs[0];
		}
		return $arr;
	}
	
	static function getFieldType($fields,$field){
		$type = $fields[$field];
		echo  DataList::$types[$type];
	}
	
	
	static function getWhereSqlAndParas($get,$db,$table,&$paras=array()){
		$fields = DataList::getFields($db,$table);
		$sql = '';
		if(isset($get['sh'])){
			foreach ($get['sh'] as $key=>$arr){
				$sql .= ' and '.$key.' '.DataList::$symbol[$arr['t']].' ?';
				if($arr['t'] == '2'){
					$paras[]='%'.iconv("gb2312","utf-8",$arr['v']).'%';
				}else{
					$paras[]=iconv("gb2312","utf-8",$arr['v']);
				}
			}
		}
		return $sql==''?'':substr($sql,4);
	}
	
	static function getOrderBySql($get){
		if(isset($get['sort_field'])){
			return array($get['sort_field'].(isset($get['sort_val']) && $get['sort_val']=='1'?' asc':' desc'));
		}
		return array();
	}
	static function getPage($countRow,$page,$maxresult,&$total=0){
		$total = (int)(($countRow + $maxresult -1)/$maxresult);
		if($page > $total){
			$page = $total;
		}
		return $page;
	}
	
	static function getFirstIndex($page,$maxresult){
		return ($page-1)*$maxresult;
	}
	
	
	
}










